package com.talking.controller;

import com.talking.pojo.Message;
import com.talking.pojo.MessageType;
import com.talking.pojo.ResponseType;
import com.talking.pojo.User;
import com.talking.service.MailService;
import com.talking.service.UserService;
import com.talking.tools.MailCode;
import com.talking.tools.ThreadPool;

import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author yun
 * 这个类主要是用来监听
 * 没有登录时，客户端发起的登录、注册、找回密码请求
 */
public class ServerThread extends Thread{
    private Socket client;
    private ObjectOutputStream outputStream;
    private ObjectInputStream inputStream;
    private Message outMsg;
    private Message inMSG;
    private volatile boolean isRunning;

    public ServerThread(Socket client){
        this.client = client;
        this.isRunning = true;

        try {
            inputStream = new ObjectInputStream(client.getInputStream());
            outputStream = new ObjectOutputStream(client.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void run() {
        while (isRunning){
            try {
                System.out.println("\n开始接收消息");
                inMSG = (Message) inputStream.readObject();

                switch (inMSG.getMessageType()) {

//                    //邮箱是否存在
//                    case MessageType.MAIL_IS_EXITED:
//                        System.out.println("接收请求：邮箱是否存在");
//                        this.mailIsExit();
//                        break;

                    //创建验证码，并且发送验证码
                    case MessageType.GET_MAIL_CODE:
                        System.out.println("接受请求：创建验证码");
                        this.getMailCode();
                        break;

                     //验证邮箱code
                    case MessageType.VERIFY_CODE:
                        System.out.println("接收请求：验证邮箱code");
                        this.verifyCode();
                        break;

                    //注册
                    case MessageType.REGISTER:
                        System.out.println("注册");
                        this.register();
                        break;

                    //找回密码
                    case MessageType.UPDATE_USER_MSG:
                        System.out.println("找回密码");
                        this.retrieve();
                        break;

                    //登录功能
                    case MessageType.LOGIN:
                        System.out.println("登录功能");
                        this.login();

                        break;

                    default:
                        System.out.println("监听到其他请求");
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                isRunning = false;
                this.closeAll();
            }
    }
    }

    //验证邮箱是否存在
    private boolean mailIsExit() throws IOException {
        String user_mail = (String) inMSG.getContent();
        return new MailService().mailIsExited(user_mail);
    }

    //创建验证码
    private void getMailCode() throws IOException {
        outMsg = new Message();
        String mail = (String) inMSG.getContent();

        //用于判断是注册，还是找回密码
        String kind = inMSG.getResponseContent();
        boolean isExited = mailIsExit();


        if (kind.equals("register")){
            if(isExited){
               outMsg.setResponseType(false);
               outMsg.setResponseContent("邮箱已注册");
            }else {
                MailService mailService = new MailService();
                mailService.createMailCode(mail);
                String mailCode = mailService.getMailCode(mail);
                MailController controller = new MailController(mail, mailCode);
                boolean temp = controller.sendMail();
                String tips = "";
                if (temp)
                    tips = "邮箱发发送成功，请注意查收！";
                else
                    tips = "邮箱发送失败";
                outMsg.setResponseType(temp);
                outMsg.setResponseContent(tips);
            }
        }else if (kind.equals("retrieve")){
            if (!isExited){
                outMsg.setResponseType(false);
                outMsg.setResponseContent("邮箱未注册!");
            }else{
                MailService mailService = new MailService();
                mailService.createMailCode(mail);
                String mailCode = mailService.getMailCode(mail);
                MailController controller = new MailController(mail, mailCode);
                boolean temp = controller.sendMail();
                String tips = "";
                if (temp)
                    tips = "邮箱发发送成功，请注意查收！";
                else
                    tips = "邮箱发送失败";
                outMsg.setResponseType(temp);
                outMsg.setResponseContent(tips);
            }
        }

        outputStream.writeObject(outMsg);



    }

    //验证密码
    private void verifyCode() throws IOException {
        outMsg = new Message();
        outMsg.setMessageType(MessageType.VERIFY_CODE);
        String mail2 = ((User) inMSG.getContent()).getUser_mail();
        String code = ((User) inMSG.getContent()).getUser_pwd();
        String tempCode = MailCode.getCode(mail2);
        outMsg.setResponseType(tempCode.equals(code));

        outputStream.writeObject(outMsg);
    }

    //注册
    private void register() throws IOException {
        outMsg = new Message();
        User newUser = (User) inMSG.getContent();
        UserService userService1 = new UserService();
        System.out.println(newUser.getHead_source().toString());
        int temp = userService1.insertUserService(newUser);
        outMsg.setMessageType(MessageType.REGISTER);
        if (temp == 1) {
            outMsg.setResponseType(true);
        } else {
            outMsg.setResponseType(false);
        }
        outputStream.writeObject(outMsg);
    }

    //找回密码
    private void retrieve() throws IOException {
        UserService userService2 = new UserService();
        outMsg = new Message();
        User reUser = (User) inMSG.getContent();
        int i = userService2.updateUserMessService(reUser);
        if (i==1)
            outMsg.setResponseType(true);
        else
            outMsg.setResponseType(false);
        outputStream.writeObject(outMsg);
    }


    //登录功能
    private void login() throws IOException {
        User inUser = (User) inMSG.getContent();         //接收到的用户
        ReceiveThread clientSocket;           //用户线程

        //查看线程池是否存在这个线程

        UserService userService = new UserService();
        Message message = new Message();

        User user = userService.getUserByIDAndPwdService(inUser);
        message.setMessageType(MessageType.LOGIN);
        message.setContent(user);

        //判断账号密码是否正确，是否存在这个对象
        if (user != null) {
            if (ThreadPool.getThread(user.getUser_id()) == null) {
                clientSocket = new ReceiveThread(client, inputStream, outputStream);
                ThreadPool.addThread(user.getUser_id(), clientSocket);
                message.setResponseType(true);      //写入响应消息，登录成功成功了
                outputStream.writeObject(message);

                clientSocket.start();
                isRunning = false;
            } else {
                System.out.println("存在线程");
                message.setResponseType(false);
                message.setResponseContent("用户已登录");
                outputStream.writeObject(message);
            }

        } else {
            message.setResponseType(false);
            message.setResponseContent("账号或密码错误");
            outputStream.writeObject(message);

        }
    }

    private void closeAll(){
        try {
            Closeable[] closeables = new Closeable[]{client, inputStream, outputStream};
            for (Closeable closeable : closeables) {
                closeable.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
